package in.abip.chisame;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import in.abip.chisame.model.Camera;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class CameraActivity extends ChisameActivity {
	private Camera _model = null;
	
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_activity);
        bindHome();
        changeTitle();
		runOnUiThread(
			new Runnable(){
				public void run() {
					play();
				}
			}
		);
    }
	
	/** Change title */
	private void changeTitle() {
		Camera camera = loadModel();
		TextView text = (TextView) findViewById(R.id.title);
		text.setText(camera.name);
	}
	
	private Camera loadModel() {
		if (_model == null) {
			Bundle bundle = getIntent().getExtras();
			Integer cameraId = bundle.getInt("cameraId");
			_model = (Camera) Camera.model().findByPk(cameraId);
		}
		return _model;
	}
	
	private void play() {
		Camera camera = loadModel();
		VideoView video = (VideoView) findViewById(R.id.video);
		try {
			final String path = camera.url;
			if (path == null || path.length() == 0) {
				Toast.makeText(
					this,
					"File URL/path is empty",
					Toast.LENGTH_SHORT
				).show();
			} else {
				video.setVideoPath(getVideo(path));
				video.start();
				video.requestFocus();
			}
		} catch (Exception e) {
			if (video != null) {
				video.stopPlayback();
			}
		}
	}
	
	private String getVideo(String path) throws IOException {
		if (!URLUtil.isNetworkUrl(path)) {
			return path;
		} else {
			URL url = new URL(path);
			URLConnection cn = url.openConnection();
			cn.connect();
			InputStream stream = cn.getInputStream();
			if (stream == null)
				throw new RuntimeException("stream is null");
			File temp = File.createTempFile("mediaplayertmp", "dat");
			temp.deleteOnExit();
			String tempPath = temp.getAbsolutePath();
			FileOutputStream out = new FileOutputStream(temp);
			byte buf[] = new byte[128];
			do {
				int numread = stream.read(buf);
				if (numread <= 0) break;
				out.write(buf, 0, numread);
			} while (true);
			try {
				stream.close();
			} catch (IOException ex) {}
			return tempPath;
		}
	}
	
	/** Bind home button click. */
	protected void bindHome() {
		OnClickListener listener = new OnClickListener() {
			public void onClick(View view) {
				CameraActivity.this.finish();
			}
		};
		View view = (View) findViewById(R.id.home);
		view.setOnClickListener(listener);
	}
}
